<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="进程与线程," />





  <link rel="alternate" href="/blog/atom.xml" title="伏窗尾的猫" type="application/atom+xml" />






<meta name="description" content="一、进程函数　　进程——进程是独立功能的程序关于某个数据集合上的一次运行活动！">
<meta name="keywords" content="进程与线程">
<meta property="og:type" content="article">
<meta property="og:title" content="学习之路 —— 进程与线程　　（二）">
<meta property="og:url" content="http://eidolon_x.gitee.io/blog/2018/09/20/学习之路——进程/index.html">
<meta property="og:site_name" content="伏窗尾的猫">
<meta property="og:description" content="一、进程函数　　进程——进程是独立功能的程序关于某个数据集合上的一次运行活动！">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://eidolon_x.gitee.io/blog//eidolon_x.gitee.io/blog/2018/09/20/学习之路——进程/exec函数族.png">
<meta property="og:updated_time" content="2021-01-18T07:27:02.921Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="学习之路 —— 进程与线程　　（二）">
<meta name="twitter:description" content="一、进程函数　　进程——进程是独立功能的程序关于某个数据集合上的一次运行活动！">
<meta name="twitter:image" content="http://eidolon_x.gitee.io/blog//eidolon_x.gitee.io/blog/2018/09/20/学习之路——进程/exec函数族.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://eidolon_x.gitee.io/blog/2018/09/20/学习之路——进程/"/>





  <title>学习之路 —— 进程与线程　　（二） | 伏窗尾的猫</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">伏窗尾的猫</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://eidolon_x.gitee.io/blog/blog/2018/09/20/学习之路——进程/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="喵呜">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/1.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="伏窗尾的猫">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">学习之路 —— 进程与线程　　（二）</h1>
        

        <div class="post-meta">
		
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-09-20T13:58:20+08:00">
                2018-09-20
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2021-01-18T15:27:02+08:00">
                2021-01-18
              </time>
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/学习之路/" itemprop="url" rel="index">
                    <span itemprop="name">学习之路</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/blog/2018/09/20/学习之路——进程/" class="leancloud_visitors" data-flag-title="学习之路 —— 进程与线程　　（二）">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">热度&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
				 <span>℃<span>
             </span>
          

          

		  
			  <span class="post-meta-divider">|</span>
			  <span id="busuanzi_value_page_pv"></span>次阅读
		  
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="一、进程函数"><a href="#一、进程函数" class="headerlink" title="一、进程函数"></a>一、进程函数</h1><p></p><p style="background-color:rgb(125,255,0)">　　进程——进程是独立功能的程序关于某个数据集合上的一次运行活动！<br><a id="more"></a></p>
<h2 id="1-1-创建进程函数"><a href="#1-1-创建进程函数" class="headerlink" title="1.1 创建进程函数"></a>1.1 创建进程函数</h2><pre><code>头文件： #include &lt;unistd.h&gt;
原型： pid_t fork(void);
功能：创建一个进程 
返回值：子进程 返回0 父进程 返回子进程的ID 
</code></pre><p>fork简介：fork函数创建了一个新的进程，新的进程即子进程将复制父进程所有的数据与指令，子进程拥有独立的内存空间以及系统资源。</p>
<p>问题一：fork 成功后子进程从哪里开始执行？</p>
<p>　　从调用完fork后面的语句处开始执行！</p>
<p>问题二：父子进程的执行顺序是怎样的？</p>
<p>　　由时间片轮转调度决定，没有固定的执行顺序。</p>
<p>问题三：什么是时间片？</p>
<p>　　时间片：为实现并发，每个进程被分配一个时间段，称作它的时间片，即该进程允许运行的时间。若时间片结束进程还在运行，则cpu将被剥夺并分配给另一个进程，若进程在时间片结束前阻塞或结束，则cpu当即切换。系统内进程按时间顺序排成一个队列，每次调度，系统都将cpu分配给队内首进程，此进程用完它的时间片后被移动到队列的末尾，接着下一个执行。<br>　　时间片过短：导致过多的进程切换，降低效率。<br>　　时间片过长：引起对短的交互请求响应变差。</p>
<h2 id="1-2-获取标识码函数"><a href="#1-2-获取标识码函数" class="headerlink" title="1.2 获取标识码函数"></a>1.2 获取标识码函数</h2><pre><code>头文件： #include &lt;unistd.h&gt;
        #include &lt;sys/types.h&gt;
原型： pid_t getpid(void); //获取本身ID 
      pid_t getppid(void);//获取父进程ID 
功能：获取进程号 
返回值：返回所获取的PID
</code></pre><h2 id="1-3-进程退出函数"><a href="#1-3-进程退出函数" class="headerlink" title="1.3 进程退出函数"></a>1.3 进程退出函数</h2><p>exit:</p>
<pre><code>头文件：#include&lt;stdlib.h&gt;
原型：void exit(int status)；
功能：用来退出进程，进行清除操作
参数： 退出码，stasus用来存返回值。
</code></pre><p>_exit:</p>
<pre><code>头文件：#include&lt;unistd.h&gt;
原型：void _exit(int status);
功能：用来退出进程，立即退出
参数： 退出码，stasus用来存返回值。
</code></pre><p>_Exit:</p>
<pre><code>头文件：#include&lt;stdlib.h&gt;
原型：void _Exit(int status);
功能：用来退出进程，立即退出
参数： 退出码，stasus用来存返回值。
</code></pre><p>进程死亡：自杀与被杀。自杀：自然死亡与调用退出函数。<br>思考：<br>问题一：return和exit有什么区别？</p>
<p>a.exit是一个函数，有参数。exit执行完后把控制权交给系统。 </p>
<p>b.return是函数执行完后的返回。renturn执行完后把控制权交给调用函数。</p>
<p>问题二：exit与_exit有什么异同？</p>
<p>相同点：都是用来终止进程的，执行这两个函数时，系统无条件终止所有操作，清除数据，终止进程运行。<br>不同点：_exit执行后立即返回给内核，exit先执行一些清除操作再将控制权交给内核。<br>清除操作：刷新流（stdin，stdout …）,将缓冲区的数据处理完成。</p>
<p>c.通过实例来区别<br>实例1：exit.c</p>
<blockquote>
<p>1 #include “stdio.h”<br>2 #include “stdlib.h”<br>3<br>4 int main()<br>5 {<br>6 printf(“using exit—-\n”);<br>7 printf(“This is the content in buffer”);<br>8 exit(0);<br>9 } </p>
</blockquote>
<p>执行结果：</p>
<blockquote>
<p>using exit—-<br>This is the content in buffer</p>
</blockquote>
<p>实例2：_exit.c</p>
<blockquote>
<p>1 #include”stdio.h”<br>2 #include”unistd.h”<br>3<br>4 int main(void)<br>5 {<br>6 printf(“using _exit–\n”);<br>7 printf(“This is the content in buffer”);<br>8 _exit(0);<br>9 }</p>
</blockquote>
<p>执行结果：</p>
<blockquote>
<p>using exit—-</p>
</blockquote>
<p>printf函数就是使用缓冲I/O的方式，该函数在遇到“\n”换行符时自动的从缓冲区中将记录读出。所以exit()将缓冲区的数据写完后才退出，而_exit()函数直接退出。 </p>
<h2 id="1-4等待子进程结束函数"><a href="#1-4等待子进程结束函数" class="headerlink" title="1.4等待子进程结束函数"></a>1.4等待子进程结束函数</h2><p>wait:</p>
<pre><code>头文件：#include &lt;sys/types.h&gt;
       #include &lt;sys/wait.h&gt;
原型：pid_t wait(int *status);
功能：等待任意一个子进程状态改变
参数： 退出码，stasus用来存子进程返回值。
返回值：成功返回 等待到的子进程进程号

    失败返回-1 同时errno被设置
</code></pre><p>waitpid    :</p>
<pre><code>头文件：#include &lt;sys/types.h&gt;
       #include &lt;sys/wait.h&gt;
原型：pid_t waitpid(pid_t pid, int *status, int options);
功能：等待任意一个子进程状态改变
参数： pid :指定要等待的进程号 
    stasus :用来存子进程返回值。
    options :等待模式：0 表示默认选项 阻塞等待
                WNOHANG 非阻塞等待 假设此时没有子进程退出就立刻返回 不用等待！
返回值：成功返回 等待到的子进程进程号
       失败返回-1 同时errno被设置
</code></pre><p>退出码解析：status用来保存子进程的退出状态的信息，用以下宏来解析。</p>
<p>WIFEXITED（status） ：如果为真，子进程正常退出。</p>
<p>WEXITSTATUS (status) ：返回子进程的退出码<br>正常退出 main函数的返回值或者exit _Exit _exit 的参数<br>WIFSIGNALED （status） ：如果为真则表示这个子进程是被一个信号干掉的！<br>WCONTINUED （status）  ：如果为真表示 这个子进程是被信号唤醒的！</p>
<h1 id="二、exec函数族"><a href="#二、exec函数族" class="headerlink" title="二、exec函数族"></a>二、exec函数族</h1><p></p><p style="background-color:rgb(125,255,0)">　　让另外一个程序文件的数据和指令集合 替换 之前拷贝的数据指令！注意这里的替换只能替换 用户数据和指令 系统数据无法替换！</p>
<p>如图所示：<img src="/blog//eidolon_x.gitee.io/blog/2018/09/20/学习之路——进程/exec函数族.png" alt="进程状态"></p>
<h2 id="1-1综述exec函数族"><a href="#1-1综述exec函数族" class="headerlink" title="1.1综述exec函数族"></a>1.1综述exec函数族</h2><pre><code>&gt;头文件：#include &lt;unistd.h&gt;
原型：#include &lt;unistd.h&gt;
extern char **environ;
int execl(const char *path,const char *arg, ...);
int execlp(const char *file, const char *arg, ...);
int execle(const char *path,const char *arg,..., char * const envp[]);
int execv(const char *path,char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execve(const char *file,char *const argv[],char *const envp[]);
功能： exec函数族装入并运行程序path/file，并将参数arg0(arg1, arg2, argv[], envp[])传递给子程序
参数： path :要运行的程序 
      arg  :存放参数。
返回值：出错返回-1，
</code></pre><p>l：list：希望接收到以逗号分隔的参数列表，列表以NULL指针作为结束标志。<br>　　　　　把要执行的那个程序文件的参数，以list的形式输出。<br>v：vector：希望接收到一个以NULL结尾的字符串数组的指针（char* argv[]）<br>　　    　　　把要执行的程序文件的参数 以向量即数组的方式出现<br>p:path：环境变量：整个系统中任何一个进程都可以访问的变量。<br>　　　　　一个以NULL结尾的字符串数组指针，函数可以DOS的PATH变量查找子程序文件<br>e:envp：函数传递指定参数envp，允许改变子进程的环境，无后缀e时，子进程使用当前程序的环境。<br>是不是看的头皮发麻？实践出真知。实例如下：</p>
<h2 id="2-1-头文件及字符串数组指针的声明"><a href="#2-1-头文件及字符串数组指针的声明" class="headerlink" title="2.1 头文件及字符串数组指针的声明"></a>2.1 头文件及字符串数组指针的声明</h2><pre><code>#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;unistd.h&gt;
#include &lt;string.h&gt;
#include &lt;errno.h&gt;

int main(int argc, char *argv[])
{
  //以NULL结尾的字符串数组的指针，适合包含v的exec函数参数
  char *arg[] = {&quot;ls&quot;, &quot;-a&quot;, NULL};
｝
</code></pre><h2 id="2-2-创建子进程并调用函数execl"><a href="#2-2-创建子进程并调用函数execl" class="headerlink" title="2.2 创建子进程并调用函数execl"></a>2.2 创建子进程并调用函数execl</h2><ul>
<li><p>execl 中希望接收以逗号分隔的参数列    表，并以NULL指针为结束标志</p>
<p>  if( fork() == 0 )<br>  {</p>
<pre><code>// in clild 
printf( &quot;1------------execl------------\n&quot; );
if( execl( &quot;/bin/ls&quot;, &quot;ls&quot;,&quot;-a&quot;, NULL ) == -1 )
{
  perror( &quot;execl error &quot; );
  exit(1);
}
</code></pre><p>  }</p>
</li>
</ul>
<h2 id="2-3-创建子进程并调用函数execv"><a href="#2-3-创建子进程并调用函数execv" class="headerlink" title="2.3 创建子进程并调用函数execv"></a>2.3 创建子进程并调用函数execv</h2><ul>
<li>execv中希望接收一个以NULL结尾的字符串数组的指针<pre><code>if( fork() == 0 )
{
  printf(&quot;2------------execv------------\n&quot;);
  if( execv( &quot;/bin/ls&quot;,arg) &lt; 0)
  {
    perror(&quot;execv error &quot;);
    exit(1);
  }
}
</code></pre></li>
</ul>
<h2 id="2-4-创建子进程并调用-execlp"><a href="#2-4-创建子进程并调用-execlp" class="headerlink" title="2.4 创建子进程并调用 execlp"></a>2.4 创建子进程并调用 execlp</h2><ul>
<li>l 　希望接收以逗号分隔的参数列表，列表以NULL指针作为结束标志</li>
<li><p>p　是一个以NULL结尾的字符串数组指针，函数可以DOS的PATH变量查找子程序文件</p>
<pre><code>if( fork() == 0 )
{
  printf(&quot;3------------execlp------------\n&quot;);
  if( execlp( &quot;ls&quot;, &quot;ls&quot;, &quot;-a&quot;, NULL ) &lt; 0 )
  {
    perror( &quot;execlp error &quot; );
    exit(1);
  }
}
</code></pre></li>
</ul>
<h2 id="2-５-创建子里程并调用execvp"><a href="#2-５-创建子里程并调用execvp" class="headerlink" title="2.５ 创建子里程并调用execvp"></a>2.５ 创建子里程并调用execvp</h2><ul>
<li>v 　望接收到一个以NULL结尾的字符串数    组的指针</li>
<li><p>p　 是一个以NULL结尾的字符串数组指针，函数可以DOS的PATH变量查找子程序文件</p>
<pre><code> if( fork() == 0 )
{
   printf(&quot;4------------execvp------------\n&quot;);
   if( execvp( &quot;ls&quot;, arg ) &lt; 0 )
   {
     perror( &quot;execvp error &quot; );
     exit( 1 );
   }
</code></pre><p>   }</p>
</li>
</ul>
<h2 id="2-6-创建子进程并调用execle"><a href="#2-6-创建子进程并调用execle" class="headerlink" title="2.6 创建子进程并调用execle"></a>2.6 创建子进程并调用execle</h2><ul>
<li>l 　希望接收以逗号分隔的参数列表，列表以NULL指针作为结束标志</li>
<li><p>e　函数传递指定参数envp，允许改变子进程的环境，无后缀e时，子进程使用当前程序的环境</p>
<p>  if( fork() == 0 )<br>  {</p>
<pre><code>printf(&quot;5------------execle------------\n&quot;);
if( execle(&quot;/bin/ls&quot;, &quot;ls&quot;, &quot;-a&quot;, NULL, NULL) == -1 )
{
  perror(&quot;execle error &quot;);
  exit(1);
}
</code></pre><p>  }</p>
</li>
</ul>
<h2 id="2-7-创建子进程并调用execve"><a href="#2-7-创建子进程并调用execve" class="headerlink" title="2.7 创建子进程并调用execve"></a>2.7 创建子进程并调用execve</h2><ul>
<li>v 　希望接收到一个以NULL结尾的字符串数组的指针</li>
<li><p>e 　函数传递指定参数envp，允许改变子进程的环境，无后缀e时，子进程使用当前程序的环境</p>
<pre><code>if( fork() == 0 )
{
  printf(&quot;6------------execve-----------\n&quot;);
  if( execve( &quot;/bin/ls&quot;, arg, NULL ) == 0)
  {
   perror(&quot;execve error &quot;);
    exit(1);
  }
}
</code></pre></li>
</ul>
<h2 id="2-8-类exec函数"><a href="#2-8-类exec函数" class="headerlink" title="2.8 类exec函数"></a>2.8 类exec函数</h2><p>system：用来执行指定的命令或程序<br>    &gt;头文件:#include &lt;stdlib.h&gt;<br>     原型：int system(const char *command);<br>    参数： command 要执行的指令 或者程序<br>    返回值  失败  返回 -1<br>           成功  除此以外进程的 退出码！</p>
<p>实例：<br>    &gt;cmd[256];<br>    sprintf(cmd,”%s %s %s”,”./hello”,”1”,”2”)<br>    system(cmd);<br>总结进程：<br>    进程 就是向操作系统申请资源的最小单位！<br>    通过进程可实现并发！因为 进程就实现并发的一种机制！<br>    进程的地址空间相互独立 创建一个进程时其会拷贝父进程的所有数据和指令！<br>    进程间的数据独立！<br>文终。</p>

      
    </div>
    
    
    
	
	<div>
	  
		<div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">------ 本文结束------</div>
    
</div>
	  
	</div>
	

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    喵呜  |  喵呜
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://eidolon_x.gitee.io/blog/2018/09/20/学习之路——进程/" title="学习之路 —— 进程与线程　　（二）">http://eidolon_x.gitee.io/blog/2018/09/20/学习之路——进程/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
  <li class="post-copyright-license">
    并保留本声明和上方二维码。感谢您的阅读和支持！
  </li>
</ul>
      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/进程与线程/" rel="tag"># 进程与线程</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/09/08/hexo--搭建/" rel="next" title="简易hexo的搭建　　（一）">
                <i class="fa fa-chevron-left"></i> 简易hexo的搭建　　（一）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/09/20/学习之路 —— 进程与线程/" rel="prev" title="学习之路 —— 进程与线程　　（一）">
                学习之路 —— 进程与线程　　（一） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/1.jpg"
                alt="喵呜" />
            
              <p class="site-author-name" itemprop="name">喵呜</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">20</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index-1.html">
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

			
			  <div class="site-state-item site-state-tags">
				<a href="/blog/tags/ || tags">
				  <span class="site-state-item-count">13</span>
				  <span class="site-state-item-name">标签</span>
				</a>
			  </div>
			

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blog/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#一、进程函数"><span class="nav-text">一、进程函数</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-1-创建进程函数"><span class="nav-text">1.1 创建进程函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-2-获取标识码函数"><span class="nav-text">1.2 获取标识码函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-3-进程退出函数"><span class="nav-text">1.3 进程退出函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-4等待子进程结束函数"><span class="nav-text">1.4等待子进程结束函数</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#二、exec函数族"><span class="nav-text">二、exec函数族</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-1综述exec函数族"><span class="nav-text">1.1综述exec函数族</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-1-头文件及字符串数组指针的声明"><span class="nav-text">2.1 头文件及字符串数组指针的声明</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-2-创建子进程并调用函数execl"><span class="nav-text">2.2 创建子进程并调用函数execl</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-3-创建子进程并调用函数execv"><span class="nav-text">2.3 创建子进程并调用函数execv</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-4-创建子进程并调用-execlp"><span class="nav-text">2.4 创建子进程并调用 execlp</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-５-创建子里程并调用execvp"><span class="nav-text">2.５ 创建子里程并调用execvp</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-6-创建子进程并调用execle"><span class="nav-text">2.6 创建子进程并调用execle</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-7-创建子进程并调用execve"><span class="nav-text">2.7 创建子进程并调用execve</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-8-类exec函数"><span class="nav-text">2.8 类exec函数</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">喵呜</span>

  
</div>

<div>
<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span id="busuanzi_container_site_pv" style='display:none'>
    本站总访问量 <span id="busuanzi_value_site_pv"></span> 次
    <span class="post-meta-divider">|</span>
</span>
<span id="busuanzi_container_site_uv" style='display:none'>
    有<span id="busuanzi_value_site_uv"></span>人看过我的博客啦
</span>
</div>


  <div class="powered-by">QQ  母胎solo </div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">微信：请勿撩骚 &mdash;  v5.1.4</div>




        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("C4C53NNHHx80rdEcr9XGvVER-gzGzoHsz", "onx6D9nlRn56BhlHoI3E08PQ");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  
  <script type="text/javascript" src="/blog/js/src/exturl.js?v=5.1.4"></script>


  <!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>

</body>
</html>
